<?php
namespace app\common\model;

use think\Model;

/**
 * 归因事件模型
 * 存储用户行为事件
 */
class AttributionEvent extends Model
{
    /**
     * 数据表名
     */
    protected $table = 'gf_attribution_event';
    
    /**
     * 主键
     */
    protected $pk = 'id';
    
    /**
     * 自动时间戳
     */
    protected $autoWriteTimestamp = true;
    
    /**
     * 创建时间字段
     */
    protected $createTime = 'created_at';
    
    /**
     * 更新时间字段
     */
    protected $updateTime = false;
    
    /**
     * 字段信息
     */
    protected $schema = [
        'id' => 'int',
        'event_id' => 'string',
        'appkey' => 'string',
        'fingerprint' => 'string',
        'install_id' => 'string',
        'event_type' => 'string',
        'event_data' => 'json',
        'session_id' => 'string',
        'created_at' => 'datetime'
    ];
    
    /**
     * 事件类型常量
     */
    const EVENT_TYPE_INSTALL = 'install';
    const EVENT_TYPE_OPEN = 'open';
    const EVENT_TYPE_REGISTER = 'register';
    const EVENT_TYPE_PURCHASE = 'purchase';
    const EVENT_TYPE_CUSTOM = 'custom';
    
    /**
     * 获取事件记录
     */
    public function getByEventId($eventId)
    {
        return $this->where('event_id', $eventId)->find();
    }
    
    /**
     * 获取设备的事件记录
     */
    public function getByFingerprint($appkey, $fingerprint, $eventType = null, $limit = null)
    {
        $query = $this->where([
            'appkey' => $appkey,
            'fingerprint' => $fingerprint
        ]);
        
        if ($eventType) {
            $query->where('event_type', $eventType);
        }
        
        if ($limit) {
            $query->limit($limit);
        }
        
        return $query->order('created_at', 'desc')->select();
    }
    
    /**
     * 获取安装的事件记录
     */
    public function getByInstallId($installId, $eventType = null)
    {
        $query = $this->where('install_id', $installId);
        
        if ($eventType) {
            $query->where('event_type', $eventType);
        }
        
        return $query->order('created_at', 'desc')->select();
    }
    
    /**
     * 获取应用的事件记录
     */
    public function getByAppkey($appkey, $eventType = null, $startDate = null, $endDate = null)
    {
        $query = $this->where('appkey', $appkey);
        
        if ($eventType) {
            $query->where('event_type', $eventType);
        }
        
        if ($startDate) {
            $query->where('created_at', '>=', $startDate);
        }
        
        if ($endDate) {
            $query->where('created_at', '<=', $endDate);
        }
        
        return $query->order('created_at', 'desc')->select();
    }
    
    /**
     * 获取事件统计
     */
    public function getEventStats($appkey, $eventType = null, $startDate = null, $endDate = null)
    {
        $query = $this->where('appkey', $appkey);
        
        if ($eventType) {
            $query->where('event_type', $eventType);
        }
        
        if ($startDate) {
            $query->where('created_at', '>=', $startDate);
        }
        
        if ($endDate) {
            $query->where('created_at', '<=', $endDate);
        }
        
        return $query->field('event_type, COUNT(*) as count, COUNT(DISTINCT fingerprint) as unique_devices')
                    ->group('event_type')
                    ->select();
    }
    
    /**
     * 获取渠道事件统计
     */
    public function getChannelEventStats($appkey, $channel, $startDate = null, $endDate = null)
    {
        // 获取该渠道的安装ID列表
        $installModel = new AttributionInstall();
        $installIds = $installModel->where([
            'appkey' => $appkey,
            'channel' => $channel
        ])->where(function($query) use ($startDate, $endDate) {
            if ($startDate) {
                $query->where('install_time', '>=', $startDate);
            }
            if ($endDate) {
                $query->where('install_time', '<=', $endDate);
            }
        })->column('install_id');
        
        if (empty($installIds)) {
            return [];
        }
        
        return $this->where('appkey', $appkey)
                   ->whereIn('install_id', $installIds)
                   ->where(function($query) use ($startDate, $endDate) {
                       if ($startDate) {
                           $query->where('created_at', '>=', $startDate);
                       }
                       if ($endDate) {
                           $query->where('created_at', '<=', $endDate);
                       }
                   })
                   ->field('event_type, COUNT(*) as count, COUNT(DISTINCT fingerprint) as unique_devices')
                   ->group('event_type')
                   ->select();
    }
    
    /**
     * 获取事件趋势
     */
    public function getEventTrend($appkey, $eventType = null, $startDate, $endDate)
    {
        $query = $this->where('appkey', $appkey);
        
        if ($eventType) {
            $query->where('event_type', $eventType);
        }
        
        return $query->whereBetween('created_at', [$startDate, $endDate])
                    ->field('DATE(created_at) as date, event_type, COUNT(*) as count')
                    ->group('DATE(created_at), event_type')
                    ->order('date', 'asc')
                    ->select();
    }
    
    /**
     * 获取会话统计
     */
    public function getSessionStats($appkey, $sessionId)
    {
        return $this->where([
            'appkey' => $appkey,
            'session_id' => $sessionId
        ])->field('event_type, COUNT(*) as count, MIN(created_at) as first_event, MAX(created_at) as last_event')
          ->group('event_type')
          ->select();
    }
}